public with sharing class KATMKTConfirmKAMAdustmentController {
   public String RecordId
     {
           get
           {
               return String.valueOf(System.currentPageReference().getParameters().get('id')).substring(0,15);  
           }
           set;
     }
     public CommonMethod getCommonMethod;
     public Activity_Information__c ActivityInfo{get;set;}
     public String KASelectedValue{get;set;}
     public List<SelectOption> KAList{get;set;}
     public List<ApproveDynamicColumnEntryForETAndFG> ETEntryList{get;set;}
     public List<String> ResourceETColumnList{get;set;}
     public List<String> ResourceCostTypeColumnList{get;set;}
     public Boolean IsCheckAll{get;set;}//全选 
     public map<string,Integer> totalKaOutletList;//ka的门店总数
     public map<string,string> StatusForKaList;//ka关态列表
     
     public KATMKTConfirmKAMAdustmentController ()
     {
         ActivityInfo=[select name,Serial_Number__c,Activity_Start_Date__c,Activity_End_Date__c,Activity_Notice__c,Activity_Type__c 
                             from Activity_Information__c where id=:RecordId];
                             
         getCommonMethod=new CommonMethod();
         LoadKAOutletTotalAndStatus();
         KAList=getCommonMethod.ParticipatorKAList(RecordId,true);
         LoadList();
     }
     public PageReference QueryKAList()
     {
        // throw new CustomException (KASelectedValue);  
         LoadList();
         return null;
     }
     public void LoadKAOutletTotalAndStatus()
     {
          totalKaOutletList=new map<string,integer>();
          StatusForKaList=new map<string,string>();
         for(ParticipatorArea__c area: [select KA__c,KA_Status__c,Outlet_Sum_Total__c from ParticipatorArea__c where Activity_Name__c=:RecordId  and  KA__c!=NULL ])
         {
             if(totalKaOutletList.containsKey(area.KA__c))
             {
                 Integer num=totalKaOutletList.get(area.KA__c);
                 num+=Integer.valueOf(area.Outlet_Sum_Total__c);
                 totalKaOutletList.put(area.KA__c,num);
             }
             else
             {
                 Decimal num=area.Outlet_Sum_Total__c;
                 totalKaOutletList.put(area.KA__c,num.intValue());
             }
             StatusForKaList.put(area.KA__c,area.KA_Status__c);
         }
     }
     public void LoadList()
     {
         string sqlResourceStr='select sum(Resource_Quantity_Number__c) SumTotal, Participator_Detail_Outlet__r.Participator_Area__r.KA__c,'+
                                             ' Resource_Allocation__r.Product_Name__r.Name ResourceName '+
                                             ' from Resource_Allocation_Detail__c '+
                                             ' where Participator_Detail_Outlet__r.Participator_Area__r.KA__c!=NULL '+ 
                                             ' and ActivityId__c=\''+RecordId+'\'';
                                             
      string sqlCompetitionStr='select sum(Money__c) SumTotal,Participator_Detail_Outlet__r.Participator_Area__r.KA__c,'+
                                               ' Activity_Competition_Brand_Information__r.Competition_Cost_Type__c ResourceName'+
                                               ' from Activity_Competition_Brand_Detail__c'+ 
                                               ' where ActivityId__c=\''+RecordId+'\''+
                                               ' and Participator_Detail_Outlet__r.Participator_Area__r.KA__c!=NULL ' ;                                   
      
       if(KASelectedValue!='0' && KASelectedValue!=NULL)      
       {
            sqlResourceStr+=' and Participator_Detail_Outlet__r.Participator_Area__r.KA__c=\''+KASelectedValue+'\'';    
            sqlCompetitionStr+=' and Participator_Detail_Outlet__r.Participator_Area__r.KA__c=\''+KASelectedValue+'\'';
       }     
       sqlResourceStr+= ' GROUP BY Participator_Detail_Outlet__r.Participator_Area__r.KA__c,'+
                                             ' Resource_Allocation__r.Product_Name__r.Name'+
                                             ' order by Resource_Allocation__r.Product_Name__r.Name asc';
       sqlCompetitionStr+=' group by Participator_Detail_Outlet__r.Participator_Area__r.KA__c,'+
                                        ' Activity_Competition_Brand_Information__r.Competition_Cost_Type__c'+
                                        ' order by Activity_Competition_Brand_Information__r.Competition_Cost_Type__c asc';
                                        
       //   throw new CustomException(sqlCompetitionStr);                        
         Map<String,ApproveDynamicColumnEntryForETAndFG> mapList=new map<String,ApproveDynamicColumnEntryForETAndFG>();//资源列表
         ETEntryList=new List<ApproveDynamicColumnEntryForETAndFG>();
         List<AggregateResult> groupResourceList=Database.query(sqlResourceStr);                                                                        
         ResourceETColumnList=getCommonMethod.GetDynamicETColumnList(groupResourceList);//获取列
         
         List<AggregateResult> competitionList=DataBase.query(sqlCompetitionStr);                                                       
         ResourceCostTypeColumnList=getCommonMethod.GetDynamicETColumnList(competitionList);//获取竞品费用类型列
         
       //  System.assert(false,ResourceCostTypeColumnList);  
         for(AggregateResult rs:groupResourceList)      
         {
              
             String  resourceName=(String)rs.get('ResourceName');
             Decimal reNum=(Decimal)rs.get('SumTotal');
             String num=String.valueOf(reNum);
             if(!mapList.containsKey((String)rs.get('KA__c')))
             {   
                 List<String> resourceNumList=new String[ResourceETColumnList.size()];
                 List<String> CostTypeNumList=new String[ResourceCostTypeColumnList.size()];
                 for(integer i=0;i<CostTypeNumList.size();i++){
                    CostTypeNumList[i]=' ';
                 }
                  for(integer j=0;j<resourceNumList.size();j++){
                    resourceNumList[j]=' ';
                 }
                 
                 ApproveDynamicColumnEntryForETAndFG entry=new ApproveDynamicColumnEntryForETAndFG();
                 entry.CostTypeNumList=CostTypeNumList;
                 entry.IsCheck=false;
                 if(StatusForKaList.get((String)rs.get('KA__c'))=='KAM已提交')
                     entry.ApproveStatus='待审批';
                 else if(StatusForKaList.get((String)rs.get('KA__c'))=='' || StatusForKaList.get((String)rs.get('KA__c'))==NULL)
                     entry.ApproveStatus='未提交';
                 else
                     entry.ApproveStatus=StatusForKaList.get((String)rs.get('KA__c'));
                    
                 entry.Name=(String)rs.get('KA__c');
                 entry.OutletTotalNumber=(Integer)totalKaOutletList.get((String)rs.get('KA__c'));
                  integer i=0;
                  for(String name:ResourceETColumnList){
                    if(name==resourceName)
                       resourceNumList[i]=num;
                    i++;
                  }
                entry.resourceNumList=resourceNumList;
                mapList.put((String)rs.get('KA__c'),entry);
             }else
             {
                  ApproveDynamicColumnEntryForETAndFG entry=mapList.get((String)rs.get('KA__c'));
                  integer i=0;
                    for(String name:ResourceETColumnList)
                    {
                        if(name==resourceName)
                             entry.resourceNumList[i]=num;
                       i++;
                    }
             }
         }   
         //添加竞品数据 
  
         for(AggregateResult rs:competitionList)   
         { 
             String comType=(String)rs.get('ResourceName');
             Decimal reNum=(Decimal)rs.get('SumTotal');
             String num=String.valueOf(reNum);
             //判断当某种竞品类型下的竞品明细全为null时设置总金额为0
             if(reNum==null)
                num='0.0';
             if(mapList.containsKey((String)rs.get('KA__c')))
              {
                 ApproveDynamicColumnEntryForETAndFG entry=mapList.get((String)rs.get('KA__c'));
                 integer i=0;
                 for(String name:ResourceCostTypeColumnList){
                    if(name==comType)
                      entry.CostTypeNumList[i]=num;
                 i++;
                  }     
                  mapList.put((String)rs.get('KA__c'),entry);
             }else{
                   List<String> resourceNumList=new String[ResourceETColumnList.size()];
                   List<String> CostTypeNumList=new String[ResourceCostTypeColumnList.size()];
                   for(integer i=0;i<CostTypeNumList.size();i++){
                    CostTypeNumList[i]=' ';
                    }
                  for(integer j=0;j<resourceNumList.size();j++){
                    resourceNumList[j]=' ';
                   }
                 
                  ApproveDynamicColumnEntryForETAndFG entry=new ApproveDynamicColumnEntryForETAndFG();
                 entry.CostTypeNumList=CostTypeNumList;
                 entry.IsCheck=false;
                 if(StatusForKaList.get((String)rs.get('KA__c'))=='KAM已提交')
                     entry.ApproveStatus='待审批';
                 else if(StatusForKaList.get((String)rs.get('KA__c'))=='' || StatusForKaList.get((String)rs.get('KA__c'))==NULL)
                     entry.ApproveStatus='未提交';
                 else
                     entry.ApproveStatus=StatusForKaList.get((String)rs.get('KA__c'));
                    
                 entry.Name=(String)rs.get('KA__c');
                 entry.OutletTotalNumber=(Integer)totalKaOutletList.get((String)rs.get('KA__c'));
              
                  integer i=0;
                   for(String name:ResourceCostTypeColumnList){
                        if(name==comType)
                          entry.CostTypeNumList[i]=num;
                     i++;
                  }
                    
                entry.resourceNumList=resourceNumList;
                mapList.put((String)rs.get('KA__c'),entry);
          }



           }    
             ETEntryList=mapList.values();
     }
     public PageReference AgreeApproveAction()
     {
        ApproveKAList('已审批');
        boolean flag=true;
        for(ParticipatorArea__c area:[select KA__c, KA_Status__c from ParticipatorArea__c where Activity_Name__c=:RecordId and KA__c!=NULL])
        {
            if(area.KA_Status__c !='已审批')
            {
                flag=false;
                break;
            }
        }
        //发送邮件给SRTM
        if(flag)
        {
           String BodyString='【'+ActivityInfo.Name+'】活动已发起，请登陆到凤凰系统调整资源，谢谢！';
           String rg=getCommonMethod.getUserRegion();
           String subject='【'+ActivityInfo.Name+'】活动已发起';//+ActivityInit.Name;getUserEmailAddress
         
           if(ActivityInfo.Activity_Type__c=='SSY'){
                EmailHander.SendMail(BodyString,getCommonMethod.getUserEmailAddress('SRTM',RecordId),subject,'',null);
           }else if(ActivityInfo.Activity_Type__c=='KA'){
                EmailHander.SendMail(BodyString,getCommonMethod.getToAddress(RecordId),subject,'',null);//发送给ASM
                 // System.assert(false,getCommonMethod.getToAddress(rg,RecordId));
           }
        }
         return null;
     }
     public PageReference RejectResourceApprovalAction()
     {
         ApproveKAList('拒绝');
         return null;
     }
   /*  public PageReference RejectComptitionApprovalAction()
     {
         ApproveKAList('拒绝(竞品费用填写不合理)');
         return null;
     }*/
     
     public void ApproveKAList(string approvelStr)
     {
          List<string> kaList=new List<string>();
          string filter='';
         for(ApproveDynamicColumnEntryForETAndFG entry:ETEntryList)
         {
             if(entry.IsCheck)
             {
                 if(entry.ApproveStatus=='待审批')
                 {
                     if(filter!='')
                         filter+=' or ';
                    filter+=' Key_Account__c includes(\''+entry.name+'\')';
            //        filter+=' Key_Account__c like \'%'+entry.name+'%\'';  includes(\''+area.KA__c+'\')
                     kaList.add(entry.Name);
                     entry.ApproveStatus=approvelStr;
                     entry.IsCheck=false;
                 }
             }
         }
         if(kaList.size()>0)
         {
             List<ParticipatorArea__c> pAreaList=[select id,KA_Status__c from ParticipatorArea__c where Activity_Name__c=:RecordId and KA__c in:kaList];
             for(ParticipatorArea__c area:pAreaList)
             {
                 area.KA_Status__c=approvelStr;
             }
             update pAreaList;
             
             if(approvelStr=='拒绝')
             {
                 String ka='KAM';
                 List<string> emailList=new List<string>();
                 for(User u:Database.query('select Email from User where Title_Functional__c=\''+ka+'\' and'+filter))
                 {
                    emailList.add(u.Email);
                 }
                  //发送邮件到KAM
              //    System.assert(false,emailList);
                     String BodyString='您好，您提交的活动已被拒绝!';
                     String subject='您好，您提交的活动已被拒绝!请重新登陆凤凰系统进行【'+ActivityInfo.Name+'】'+'活动调整';
                     EmailHander.SendMail(BodyString,emailList,subject,'',null);
             }
         }
     }
     
     public PageReference Cancel()
     {
         PageReference pr=new pageReference('/'+RecordId);
         pr.setRedirect(true);
         return pr;
     }
}